library(ggplot2)
library(readstata13)
library(cregg)
library(tidyverse)
library(stargazer)

rm(list = ls())

#Main Paper####
##Data Import and Formatting####

data1<-read.dta13("Code/Study2/merged_conjoint_study2.dta")
colnames(data1)
with(data1, table(id))

#Four respondents did not have a record of seeing conjoints.
data1<-data1 %>% filter(resp_id !="1071")
data1<-data1 %>% filter(resp_id !="1261")
data1<-data1 %>% filter(resp_id !="136")
data1<-data1 %>% filter(resp_id !="92")

#Code Party ID 

data1<-data1 %>%
  mutate(pid3_lean = case_when(
    Q7 == 1 | Q10 == 2 ~ 'Democrat',
    Q7 == 2 | Q10 == 1 ~ 'Republican',
    Q10 == 3 ~ 'Independent'))
data1$pid3_lean<-as.factor(data1$pid3_lean)


#Shrink dataset

data2<-data1 %>% select(c("Y_choice","resp_id","choiceNum","locNum","id","registration","speech","votemethod","wait","watcher", "pid3_lean", "diff", "Q52"))
data2 <- data2 %>% filter(Y_choice !="NA")

data3<-data2 %>%
  mutate(Voter_ID=recode_factor(id,
                                "None Required" = "None",
                                "Signature on Sign in" = "Signature",
                                "Photo ID" = "ID",
                                " Photo ID + Signature on Sign in" = "Sig. and ID"),
         Registration=recode_factor(registration, 
                                    "Registration must be complete 30 days before the election"="30 days prior",
                                    "Registration must be complete 8 days before the election"="8 days prior",
                                    "Same day registration not permitted" = "No same day",
                                    "Same day registration permitted with proper ID" = "Same day with ID",
                                    "Same day registration permitted"="Same day allowed"),
         Speech=recode_factor(speech,
                              "No campaigning allowed within 100 feet"="< 100 ft",
                              "No campaigning allowed within 50 feet"="< 50 ft",
                              "No campaigning allowed within the building"="No campaigning",
                              "No restriction on campaigning"="No restriction"),
         Vote_Method=recode_factor(votemethod,
                                   "Machine (touchscreen), no paper ballot printed"="Machine/no ballot",
                                   "Machine (touchscreen), prints paper ballot"="Machine/ballot",
                                   "Machine (touchscreen), prints paper ballot with automatic audit"="Machine/ballot/automatic audit",
                                   "Paper ballot, machine counted"="Paper/machine count"),
         Wait_Time=recode_factor(wait,
                                 "<10 minutes"="<10 min.",
                                 "10-30 minutes"="10-30 min.",
                                 "30 minutes-1 hour"="30-60 min.",
                                 "1-3 hours"="1-3 hr.",
                                 "3+hours"="3+ hr."),
         Poll_Watchers=recode_factor(watcher,
                                     "None present"="None present",
                                     "Both Democratic and Republican Party watchers" = "Both D & R", 
                                     "Both Democratic and Republican Party watchers with identification badges" = "Both D & R/Badges",
                                     "Only Democratic Party watchers" = "Only D", 
                                     "Only Democratic Party watchers with identification badges" = "Only D/Badges", 
                                     "Only Republican Party watchers" = "Only R", 
                                     "Only Republican Party watchers with identification badges" = "Only R/Badges"))
with(data3, table(Poll_Watchers))
with(data3, table(Wait_Time))
with(data3, table(Vote_Method))
with(data3, table(Speech))
with(data3, table(Registration))
with(data3, table(Voter_ID))
with(data3, table(pid3_lean))

data3<- data3 %>% mutate(PID=recode_factor(pid3_lean,
                                    "1"="Democrat",
                                    "3"="Republican"))

data3<-data3 %>% filter(Poll_Watchers !="NA")

save.dta13(data3, "analysis_dataset_study2.dta")

##Analysis 1 - AMCE#### 

output<-cj(data3, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time, id = ~ resp_id)

output

x<-plot(output)
plot_amce_study2<-x+geom_hline(yintercept=c(6,11,16,22,27), color="grey")+
  geom_point(size=3)+
  theme_bw()+
  #ggtitle("Study 2 (Original Experiment)")+
  theme(legend.position = "none")+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))
plot_amce_study2

#Figure 4
ggsave(
  "Figures/Main Paper/study2_AMCE_binary.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

##Analysis 2 - Marginal Means by Party ID#### 

data3_pid<-data3 %>%filter(PID !="NA",  PID !="Independent")
data3_pid$PID

data3_pid<-data3_pid %>% mutate(RepDem=recode_factor(pid3_lean, 
                                              "Democrat"="Dem.",
                                              "Republican"="Rep."))
with(data3_pid,RepDem)
data3_pid$RepDem<-droplevels(data3_pid$RepDem)

output<-cj(data3_pid,Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time,
           id = ~ resp_id,
           by=~RepDem,
           estimate="mm")
output
with(output, table(RepDem))

plot_mm_study2<-plot(output, group="RepDem", size=3)+aes(shape=RepDem,color=RepDem)+
  geom_hline(yintercept=c(6,11,16,22,27), color="grey")+
  scale_shape_manual(values=c(15, 16),na.translate=F) + 
  scale_color_manual(values=c("dark blue","red"), na.translate=F)+
  theme_bw()+
  #ggtitle("Study 2 (Original Experiment)")+
  theme(legend.position = "top", legend.title=element_blank())+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))
plot_mm_study2

#Figure 5 
ggsave(
  "Figures/Main Paper/study2_marginalmean_binary.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)


#Appendix####

##Difference Outcome 

###Analysis 1 - AMCE#### 

output<-cj(data3, diff~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time, id = ~ resp_id)

output

x<-plot(output)
plot_amce_study2<-x+geom_hline(yintercept=c(6,11,16,22,27), color="grey")+
  geom_point(size=3)+
  theme_bw()+
  ggtitle("Study 2 (Original Experiment)")+
  #theme(legend.position = "none")+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))
plot_amce_study2

#Figure B3 
ggsave(
  "Figures/Appendix/study2_AMCE_diff.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

###Analysis 2 - Marginal Means by Party ID#### 

data3_pid<-data3 %>%filter(PID !="NA",  PID !="Independent")
data3_pid$PID

data3_pid<-data3_pid %>% mutate(RepDem=recode_factor(pid3_lean, 
                                                     "Democrat"="Dem.",
                                                     "Republican"="Rep."))
with(data3_pid,RepDem)
data3_pid$RepDem<-droplevels(data3_pid$RepDem)


output<-cj(data3_pid,diff~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time,
           id = ~ resp_id,
           by=~RepDem,
           estimate="mm")
output
with(output, table(RepDem))


plot_mm_study2<-plot(output, group="RepDem", size=3)+aes(shape=RepDem,color=RepDem)+
  geom_hline(yintercept=c(6,11,16,22,27), color="grey")+
  scale_shape_manual(values=c(15, 16),na.translate=F) + 
  scale_color_manual(values=c("dark blue","red"), na.translate=F)+
  theme_bw()+
  #ggtitle("Study 2 (Original Experiment)")+
  theme(legend.title=element_blank())+
  theme(axis.title=element_text(size=14,face="bold"))+
  theme(axis.text=element_text(size=12))+
  theme(strip.text.x = element_text(size = 12))
plot_mm_study2

#Figure B4 
ggsave(
  "Figures/Appendix/study2_marginalmean_diff.tiff",
  device="tiff",
  width=8,
  height=10,
  dpi=300)

##AMCE by Rounds####

results_data<-data3 %>% mutate(task_num=as.factor(choiceNum))

output_by_round<-cj(results_data, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                    , id = ~ resp_id, by=~task_num, estimate="amce")
summary(output_by_round)

marginal_means_plot_by_task <- ggplot(output_by_round, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~task_num, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task
#Figure C5 
ggsave("Figures/Appendix/Study 2 - AMCE by Rounds.png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

output_by_round_watchers<-output_by_round %>% filter(feature=="Poll_Watchers")
marginal_means_plot_by_task2 <- ggplot(output_by_round_watchers, aes(y=estimate, x=fct_rev(level), color=task_num,  group=fct_rev(task_num))) +
  #facet_grid(~task_num, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.5)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.5)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task2
#Figure C6 
ggsave("Figures/Appendix/Study 2 - AMCE by Rounds (Poll Watchers Only).png",marginal_means_plot_by_task2, dpi=300, width=8, height=6)


## AMCE by Profile Order####
results_data<-data3 %>% mutate(profile_order=as.factor(locNum))

output_by_profile<-cj(results_data, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~profile_order, estimate="amce")
summary(output_by_profile)

marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~profile_order, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task
#Figure C7
ggsave("Figures/Appendix/Study 2 - AMCE by Profile Order.png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

output_by_profile_watchers<-output_by_profile %>% filter(feature=="Poll_Watchers")
marginal_means_plot_by_task <- ggplot(output_by_profile_watchers, aes(y=estimate, x=fct_rev(level), color=profile_order,  group=fct_rev(profile_order))) +
  #facet_grid(~profile_order, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.5)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.5)) + 
  theme_bw()+
  labs(col="") + theme(legend.position="top")
marginal_means_plot_by_task
#Figure C8
ggsave("Figures/Appendix/Study 2 - AMCE by Profile Order (Poll Watchers Only).png",marginal_means_plot_by_task, dpi=300, width=8, height=4)

##Subsets by State and Watcher Rules####
#Conjoint Data 

data3_tomerge<-data3 %>% rename("State_Code"="Q52") 
summary(data3_tomerge)

#State rule data 
data_state<-read.csv("state watcher rules.csv")
summary(data_state)

data_merged<-left_join(data3_tomerge, data_state, by="State_Code") %>% filter(State !="West Virginia")
summary(data_merged)

#AMCE by Rules 
data_merged2<-data_merged
data_merged2$"can_challenge"<-as.factor(data_merged2$"can_challenge")
data_merged2$"can_speak"<-as.factor(data_merged2$"can_speak")
data_merged2$"prohibit_election"<-as.factor(data_merged2$"prohibit_election")
data_merged2$"called_watchers"<-as.factor(data_merged2$"called_watchers")
data_merged2$"called_challengers"<-as.factor(data_merged2$"called_challengers")
data_merged2$"official_id"<-as.factor(data_merged2$"official_id")

summary(data_merged2)

#Can Challenge 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~can_challenge, estimate="amce")
output_by_profile<-output_by_profile %>% mutate(can_challenge=recode(can_challenge, 
                                                                     "0"="Not allowed to challenge",
                                                                     "1"="Allowed to challenge"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~can_challenge, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  ggtitle("Study 2")+
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D1 
ggsave("Figures/Appendix/State Rules/Study 2 - AMCE by State Rules (Challenge Voters).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Can Speak 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~can_speak, estimate="amce")

output_by_profile<-output_by_profile %>% mutate(can_speak=recode(can_speak, 
                                                                 "0"="Speaking to voters prohibited",
                                                                 "1"="Speaking to voters allowed"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~can_speak, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 2")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
#Figure D5 
ggsave("Figures/Appendix/State Rules/Study 2 - AMCE by State Rules (Speak to Voters).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Prohibit Election Engagement 
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~prohibit_election, estimate="amce")
summary(output_by_profile)
output_by_profile<-output_by_profile %>% mutate(prohibit_election=recode(prohibit_election, 
                                                                         "0"="Electioneering Allowed",
                                                                         "1"="Electioneering Prohibited"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~prohibit_election, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 2")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D2 
ggsave("Figures/Appendix/State Rules/Study 2 - AMCE by State Rules (Prohibit Electioneering).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Called Challenger  
output_by_profile<-cj(data_merged2, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~called_watchers, estimate="amce")
summary(output_by_profile)
output_by_profile<-output_by_profile %>% mutate(called_watchers=recode(called_watchers, 
                                                                          "0"="Not Called Poll Watchers",
                                                                          "1"="Called Poll Watchers"))



marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~called_watchers, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 2")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D4
ggsave("Figures/Appendix/State Rules/Study 2 - AMCE by State Rules (Watchers Label).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

#Required Display ID 
data_merged3<-  data_merged2 %>% filter(official_id==1 | official_id==0)
data_merged3$id_required<-droplevels(data_merged3$official_id)

output_by_profile<-cj(data_merged3, Y_choice~Poll_Watchers+Voter_ID+Registration+Speech+Vote_Method+Wait_Time
                      , id = ~ resp_id, by=~official_id, estimate="amce")
summary(output_by_profile)
output_by_profile<-output_by_profile %>% mutate(official_id=recode(official_id, 
                                                                   "0"="Not required to wear ID",
                                                                   "1"="Required to wear ID"))


marginal_means_plot_by_task <- ggplot(output_by_profile, aes(y=estimate, x=fct_rev(level), color=feature,  group=fct_rev(feature))) +
  facet_grid(~official_id, scales="free") + 
  coord_flip()  + ylab("AMCE") + xlab("") + 
  geom_point(position=position_dodge(width=.75)) + 
  ggtitle("Study 2")+
  #geom_text(aes(label=round(estimate, digits = 2)),size = 2, nudge_x=.25) +
  geom_errorbar(aes(ymin= lower, ymax= upper), size=1, width=0, position=position_dodge(width=.75)) + 
  labs(col="") + theme(legend.position="right")
marginal_means_plot_by_task
#Figure D2
ggsave("Figures/Appendix/State Rules/Study 2 - AMCE by State Rules (Required ID).png",marginal_means_plot_by_task, dpi=300, width=12, height=8)

